package com.dailyblue.java.project.estate.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.project.estate.gateway.service.EstateManagerService;
import com.dailyblue.project.estate.commons.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class LoginGlobalFilter implements Ordered, GlobalFilter {

    @Resource
    private EstateManagerService service;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 是否是登陆请求
        String uri = request.getURI().toString();
        if (!uri.contains("/login?")) {
            log.info("登陆过滤器不起作用！");
            return chain.filter(exchange);
        }
        // 获取到用户的请求
        String name = request.getQueryParams().get("username").get(0);
        String pass = request.getQueryParams().get("password").get(0);
        JsonResult result = service.login(name, pass);
        if (result.getSuccess()) {
            return success(exchange, result);
        }
        return error(exchange, result);
    }

    private Mono<Void> success(ServerWebExchange exchange, JsonResult result) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(200));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    private Mono<Void> error(ServerWebExchange exchange, JsonResult result) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(data));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
